import { useRef, useState } from "react";
import styles from "./index.module.less";
import {
	ProForm,
	ProFormInstance,
	ProFormText,
	ProFormRadio,
	ProFormSelect,
	ProFormDateRangePicker
} from "@ant-design/pro-components";
import { Affix, Button, ConfigProvider, Flex, Space, message, Row, Col } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { createLine, updateLine, getLineDetail, getSiteByScene } from "@/api/modules/line";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import dayjs from "dayjs";
import AMap from "@/components/AMap";
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { getAllJoint, getDockList } from "@/api/modules/platform";
import { cloneDeep, map, omit, forEach } from "lodash"; 
import { PageContainer } from '@ant-design/pro-layout';

type Site = {
  id: number | string;
};

export default () => {
	const formRef = useRef<ProFormInstance>();
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const [selectFields, setSelectFields] = useState<Site[]>([]);
	const [siteList, setSiteList] = useState([]);
	const [siteMarkers, setSiteMarkers] = useState<any[]>([]); //全量接驳点
	const [loopPath, setLoopPath] = useState<any>([]); //环线点位列表
	const [allSites, setAllSites] = useState<any>({});
	const [allDockList, setAllDockList] = useState<any[]>([]);

	const { loading: loadingDetail, runAsync: getDetailAsync, data: walkDetailInfo } = useRequest(getLineDetail, { manual: true });

	useEffect(() => {
		handleGetAllJoint();
		handleGetDockList();
		if (!detailId) return;
		getDetailAsync({ id: detailId }).then(async (res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				const dataSiteList = cloneDeep(data?.siteList);
				setSelectFields(dataSiteList.slice(1, -1))
				const path = map(data?.siteList, (item: any) => {
					const position = item.lonLat?.split(',')
					return [position[0], position[1]]
				})
				setLoopPath([{path}])
				const InitialData = {
					...data,
					startDock: data?.siteList?.[0]?.scId,
					endDock: data?.siteList?.[data?.siteList?.length - 1]?.scId,
				};
				// 先设置表单数据
				formRef.current?.setFieldsValue(InitialData);
				// 然后异步加载站点数据，确保 allSites 状态正确更新
				try {					
					for (let index = 0; index < (dataSiteList || []).length; index++) {
						const item = dataSiteList[index];
						if(index !== 0 && index !== dataSiteList.length - 1) {
							InitialData[`select${item.id}`] = item.id
							InitialData[`dock${item.id}`] = item.scId
						}
						if(index === 0) {
							await handleDockChange(item.scId, 'start');
						} else if (index === dataSiteList.length - 1) {
							await handleDockChange(item.scId, 'end');
						} else {
							await handleDockChange(item.scId, item.id);
						}
					}
					
					// 重新设置表单数据，包含站点选择
					formRef.current?.setFieldsValue(InitialData);
				} catch (error) {
					console.error('加载站点数据失败:', error);
				}
			}
		});
	}, []);

	const handleValuesChange = (changeValue: any) => {
		// 监听站点变化，更新地图路径
		if ('startSite' in changeValue || 'endSite' in changeValue) {
			updateLoopPath();
		}
		
		// 监听途径点变化
		Object.keys(changeValue).forEach(key => {
			if (key.startsWith('select') && changeValue[key]) {
				updateLoopPath();
			}
		});
	};

	const handleSubmit = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		let objNameArr: any = []
		const siteIdArr = map(selectFields, (item: any) => {
			const id = `select${item.id}`
			const dockId = `dock${item.id}`
			objNameArr.push(id, dockId)
			return values[id]
		})
		const newValues = omit(values, ['startSite', 'endSite', 'startDock', 'endDock', ...objNameArr])
		const requestData = {
			...newValues,
			siteIds: [values.startSite, ...siteIdArr, values.endSite]
		};
		const callback = () => {
			if (detailId) {
				updateLine({ ...requestData, id: detailId }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("更新成功");
						handleBack();
					}
				});
			} else {
				createLine({ ...requestData }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("保存成功");
						handleBack();
					}
				});
			}
		};
		formRef.current?.validateFieldsReturnFormatValue?.().then(() => {
			callback();
		});
	};

	const handleBack = () => {
		navigate("/line/list");
	};

	//获取全量站点列表 
	const handleGetAllJoint = async () => {
		getAllJoint({ page: { pageNum: 1, pageSize: 100 } }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				setSiteList(res?.data?.list)
				const result = map(res?.data?.list, (item: any) => {
					const positionArr = item.lonLat?.split(',')
					return { position: [positionArr[0], positionArr[1]] }
				})
				setSiteMarkers(result)
			}
		})
	}
	
	//获取全量月台列表
	const handleGetDockList = async () => {
		const res: any = await getDockList({ page: { pageNum: 1, pageSize: 100 } })
		if (res?.code === RESULT_CODES.SUCCESS) {
			setAllDockList(res?.data?.list); 
		}
	}

	// 添加选择框
	const handleAdd = (index: any) => {
		let result: any = cloneDeep(selectFields)
		if(selectFields.length <= 0) {
			result.push({id: Date.now() })
		} else {
			result.splice(index, 0, { id: Date.now() })
		}
		setSelectFields(result);
		// 添加途径点后更新路径
		setTimeout(() => updateLoopPath(), 100);
	};

	// 删除选择框
	const handleRemove = (index: any) => {
		let result: any = cloneDeep(selectFields)
		result?.splice(index, 1)
		setSelectFields(result);
		// 删除途径点后更新路径
		setTimeout(() => updateLoopPath(), 100);
	};

	// 处理月台选择变化
	const handleDockChange = async (value: string, id: any) => {
		if (!value) {
			// 如果值为空，清空对应的站点列表
			setAllSites((prev: any) => {
				const updated = cloneDeep(prev);
				updated[id] = [];
				return updated;
			});
			updateLoopPath();
			return;
		}
		
		try {
			const sites = await getSiteByScene({id: value});
			// 确保数据结构正确，如果 sites?.data 是数组，直接使用；如果是对象，提取 list 字段
			const siteData = Array.isArray(sites?.data) ? sites.data : sites?.data?.list || [];
			
			// 使用函数式更新确保状态正确
			setAllSites((prev: any) => {
				const updated = cloneDeep(prev);
				updated[id] = siteData;
				return updated;
			});
		} catch (error) {
			console.error('获取站点列表失败:', error);
			// 如果请求失败，清空对应的站点列表
			setAllSites((prev: any) => {
				const updated = cloneDeep(prev);
				updated[id] = [];
				return updated;
			});
		}
	};

	// 更新环线路径
	const updateLoopPath = () => {
		const values = formRef.current?.getFieldsFormatValue?.();
		if (!values) return;

		const path: any[] = [];
		
		// 添加起始站
		if (values.startSite) {
			// 先从 allSites.start 中查找，如果没找到再从 siteList 中查找
			let startSite = allSites?.start?.find((site: any) => site.id === values.startSite);
			if (!startSite) {
				startSite = siteList.find((site: any) => site.id === values.startSite);
			}
			if (startSite?.lonLat) {
				const position = startSite.lonLat.split(',');
				path.push([position[0], position[1]]);
			}
		}
		
		// 添加途径点
		selectFields.forEach((field: any) => {
			const siteId = values[`select${field.id}`];
			if (siteId) {
				// 先从 allSites[field.id] 中查找，如果没找到再从 siteList 中查找
				let site = allSites?.[field.id]?.find((s: any) => s.id === siteId);
				if (!site) {
					site = siteList.find((s: any) => s.id === siteId);
				}
				if (site?.lonLat) {
					const position = site.lonLat.split(',');
					path.push([position[0], position[1]]);
				}
			}
		});
		
		// 添加终点站
		if (values.endSite) {
			// 先从 allSites.end 中查找，如果没找到再从 siteList 中查找
			let endSite = allSites?.end?.find((site: any) => site.id === values.endSite);
			if (!endSite) {
				endSite = siteList.find((site: any) => site.id === values.endSite);
			}
			if (endSite?.lonLat) {
				const position = endSite.lonLat.split(',');
				path.push([position[0], position[1]]);
			}
		}
		
		// 更新路径和标记点
		if (path.length > 0) {
			setLoopPath([{ path }]);
			setSiteMarkers(path.map((position: any) => ({
				position: [position[0], position[1]]
			})));
		} else {
			setLoopPath([]);
			setSiteMarkers([]);
		}
	};

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: '/line/list', breadcrumbName: '环线管理' },
					{ href: '', breadcrumbName: detailId ? '编辑环线' : '新增环线' },
				],
			}}
		>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={styles.detailContainer}>
					<div className={styles.container}>
						<ProForm
							colon={false}
							submitter={false}
							formRef={formRef}
							layout="horizontal"
							onValuesChange={handleValuesChange}
							labelCol={{ span: 6 }}
						>
							<div className={styles.content_wrap}>
								<div className={styles.content}>
									<div className={styles.moduleTitle}>{detailId ? "修改环线" : "新增环线"}</div>
									<ProFormText
										label="环线名称"
										name="loopName"
										labelCol={{ span: 5 }}  // 设置label占用的栅格列数
										rules={[
											{ required: true, message: "请输入环线名称" },
										]}
									/>
									<div style={{width: '100%'}}>
										<Row className={styles.mapFieldsItem}>
											<Col span={12} className={styles.pr10}>
												<ProFormSelect
													label="起始站"
													labelCol={{ span: 10 }}  // 设置label占用的栅格列数
													name="startDock"
													rules={[{ required: true, message: "关联月台" }]}
													placeholder={"关联月台"}
													options={allDockList}
													fieldProps={{
														fieldNames: {
															label: 'scName',  // 显示文本对应的字段
															value: 'id',    // 值对应的字段
														},
														onChange: (value: any) => handleDockChange(value, 'start')
													}}
												/>
											</Col>
											<Col span={9}>
												<ProFormSelect
													name={`startSite`}
													// labelCol={{ span: 7 }}  // 设置label占用的栅格列数
													// label={'起始站'}
													options={allSites?.start}
													fieldProps={{
														fieldNames: {
															label: 'name',  // 显示文本对应的字段
															value: 'id',    // 值对应的字段
														}
													}}
												/>
											</Col>
											<Col className={styles.itemBtnGroup} span={3}>
												<Button 
													icon={<PlusOutlined />} 
													onClick={() => handleAdd(0)}
												/>
											</Col>
										</Row>
										{
											selectFields.map((field, index) => (
												<div key={field.id} className={styles.mapFieldsItem}>
													<Col span={12} className={styles.pr10}>
														<ProFormSelect
															label="途径点"
															labelCol={{ span: 10 }}  // 设置label占用的栅格列数
															name={`dock${field.id}`}
															rules={[{ required: true, message: "关联月台" }]}
															placeholder={"关联月台"}
															options={allDockList}
															fieldProps={{
																fieldNames: {
																	label: 'scName',  // 显示文本对应的字段
																	value: 'id',    // 值对应的字段
																},
																onChange: (value: any) => handleDockChange(value, field.id)
															}}
														/>
													</Col>
													<Col span={7}>
														<ProFormSelect
															key={field.id}
															name={`select${field.id}`}
															// labelCol={{ span: 7 }}  // 设置label占用的栅格列数
															// label={'途径点'}
															options={allSites?.[field.id]}
															fieldProps={{
																fieldNames: {
																	label: 'name',  // 显示文本对应的字段
																	value: 'id',    // 值对应的字段
																}
															}}
														/>
													</Col>
													<Col className={styles.itemBtnGroup} span={5}>
														<Button 
															icon={<MinusOutlined />} 
															onClick={() => handleRemove(index)}
															danger
														/>
														<Button 
															icon={<PlusOutlined />} 
															onClick={() => handleAdd(index + 1)}
														/>
													</Col>
												</div>
											))
										}
										<Row className={styles.mapFieldsItem}>
											<Col span={12} className={styles.pr10}>
												<ProFormSelect
													label="终点站"
													labelCol={{ span: 10 }}  // 设置label占用的栅格列数
													name="endDock"
													rules={[{ required: true, message: "关联月台" }]}
													placeholder={"关联月台"}
													options={allDockList}
													fieldProps={{
														fieldNames: {
															label: 'scName',  // 显示文本对应的字段
															value: 'id',    // 值对应的字段
														},
														onChange: (value: any) => handleDockChange(value, 'end')
													}}
												/>
											</Col>
											<Col span={12}>
												<ProFormSelect
													name={`endSite`}
													// labelCol={{ span: 7 }}  // 设置label占用的栅格列数
													// label={'终点站'}
													options={allSites?.end}
													fieldProps={{
														fieldNames: {
															label: 'name',  // 显示文本对应的字段
															value: 'id',    // 值对应的字段
														}
													}}
												/>
											</Col>
										</Row>
									</div>
								</div>
							</div>
						</ProForm>
						<Flex justify="right" className={styles.btns}>
							<Space size={10}>
								<Button ghost type="primary" onClick={() => navigate(-1)}>
									返回
								</Button>
								<Button type="primary" onClick={handleSubmit}>
									保存
								</Button>
							</Space>
						</Flex>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap markers={siteMarkers} polylinePaths={loopPath}/>
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
